package com.wjf.birdfish.util; 

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created on 2006-10-28
 * <p>Title: Generics的util类</p>
 * <p>Generics的util类,通过反射获得Class声明的范型Class.</p> 
 * <p>Copyright: Copyright TYDIC (c) 2006</p>
 * <p>Company: tydic.com</p>
 * @author <a href="malito:tongys@tydic.com">童永胜</a>
 * @version 1.0
 */
public class GenericsUtils {
    /**
     * Locates the first generic declaration on a class.
     *
     * @param clazz The class to introspect
     * @return the first generic declaration, or <code>null</code> if cannot be determined
     */
    public static Class getGenericClass(Class clazz) {
        return getGenericClass(clazz, 0);
    }

    /**
     * Locates  generic declaration by index on a class.
     *
     * @param clazz clazz The class to introspect
     * @param index the Index of the generic ddeclaration,start from 0.
     */
    public static Class getGenericClass(Class clazz, int index) {
        Type genType = clazz.getGenericSuperclass();

        if (genType instanceof ParameterizedType) {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

            if (params != null && params.length >= index - 1) {
                return (Class) params[index];
            }
        }
        return null;
    }
}
